package com.enki.adminplatform.config;

import com.enki.adminplatform.security.CaptchaFilter;
import com.enki.adminplatform.security.LoginFailureHandler;
import com.enki.adminplatform.security.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author yinyin
 * @create 2021/07/27 下午 4:08
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Autowired
    LoginSuccessHandler loginSuccessHandler;

    @Autowired
    CaptchaFilter captchaFilter;

    //白名单
    private static final String[] URL_WHITELIST = {

            "/login",
            "/logout",
            "/sys/auth/getCaptcha",
            "/favicon.ico",

    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //允许跨域和csrf
        http.cors().and().csrf().disable()
        //登录配置
        .formLogin()
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler)
        //禁用session
        .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        //配置拦截规则  除了白名单,其余请求均拦截
        .and()
                .authorizeRequests()
                .antMatchers(URL_WHITELIST).permitAll()
                .anyRequest().authenticated()
        .and()    //验证码校验放在用户名密码校验之前
               .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class);
    }


}
